<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\Admin\AdminAction;
use App\Models\Admin\Ucenter;


class UcenterController extends CommonController {

	public function __construct()
	{
		parent::__construct();
		$this->checkLogin();
	}
	
	/**
	 * @param int $parent_id
	 * @param int $level
	 * @param int $current
	 * @return array
	 * 递归查询子节点，适用js—tree插件
	 */
	private function selectChild($parent_id = 1,$level = 10, $current =1){
		$return = array();
		if($current > $level){
			return $return;
		}
		$current++;
		$data = DB::table('t18_user_tree')
					->select('t18_user_tree.node_id as id','t18_user_tree.parent_id as pid','tnet_reginfo.nodecode as text')
					->leftJoin('tnet_reginfo', 't18_user_tree.node_id', '=', 'tnet_reginfo.nodeid')
					->where(['parent_id' => $parent_id])
					->get();
		if($data){
			foreach($data as $k => $v){
				$children = $this->selectChild((int)$v->id,$level, $current);
				$v->state = array(
					'opened'=>true
				);
				$children ? $v->children = $children : null;
				$return[] = $v;
			}
		}
		return $return;
	}

	/**
	 * @param Request $request
	 * @return mixed
	 * 用户树列表
	 */
	public function user_tree(Request $request){
		$nodecode = $request->input('nodecode'); //手机号
		$level = $request->input('level') ? $request->input('level') : 5; //资源维度
		$userInfo = Db::table('tnet_reginfo')->where('nodecode',$nodecode)->first();
		if($userInfo){
			$parent_id = $userInfo->nodeid;
		}else{
			$parent_id = 1;
		}
		$data = DB::table('t18_user_tree')
			->select('t18_user_tree.node_id as id','t18_user_tree.parent_id as pid','tnet_reginfo.nodecode as text')
			->leftJoin('tnet_reginfo', 't18_user_tree.node_id', '=', 'tnet_reginfo.nodeid')
			->where(['node_id' => $parent_id])
			->first();
		$data->state = array(
			'opened'=>true
		);
		$data->id = (int)$data->id;
		$data->children = $this->selectChild($parent_id,$level);
		return view('admin.ucenter.user_tree',[
			'tree' => json_encode($data),
			'nodecode' => $nodecode,
			'level' => $level
		]);
	}
	
	/**
	 * 用户列表
	 **/
	public function ucenter_list(Request $request) {
		if($request->isMethod('post')) { //搜索
			//查询用户基本信息
			$nodecode = trim($request->input('user_account'));
			if($nodecode) {
				$user_info = DB::table('tnet_reginfo')->where('nodecode','like',$nodecode.'%')->orderBy('nodeid', 'desc')->paginate(20);
				$user_info->post_nodecode = $nodecode;
			}else {
				//查询用户基本信息
				$user_info = DB::table('tnet_reginfo')->orderBy('nodeid', 'desc')->paginate(20);
				$user_info->post_nodecode = '';
			}
		}else { //非搜索
			//查询用户基本信息
			$user_info = DB::table('tnet_reginfo')->orderBy('nodeid', 'desc')->paginate(20);
			$user_info->post_nodecode = '';
		}
		//查询用户推荐人信息和用户等级信息
		foreach($user_info as $key => $value) {
			//查询用户等级
			$level_info = DB::table('t18_user_tree')->where(['node_id'=>$value->nodeid])->first();
			//保存用户等级到用户基本信息的数组中
			$user_info[$key]->level 	  = $level_info ? $level_info->user_level : '';
			if($value->introducer) {
				//查查用户推荐人
				$intro_id = $value->introducer;
//				dd($intro_id);
				$parent_info = DB::table('tnet_reginfo')->where(['nodeid'=>$intro_id])->first();
//				dd($intro_id,$parent_info);
				//保存推荐人信息和用户等级到用户基本信息的数组中
				$user_info[$key]->mobileno = $parent_info->nodecode;
			}else {
				//如果用户不存在推荐人，则保存空字符串
				$user_info[$key]->mobileno = '';
			}
		}
		//展示模板
		return view('admin.ucenter.ucenter_list',['user_info'=>$user_info]);
	}

	/**
	 * 用户购买的VIP套餐
	 **/
	public function ucenter_vip_cost(Request $request) {
		//获取用户名
		$nodename = $request->input('nodename');
		//查询用户购买的VIP套餐
		$node_id = $request->input('id');
		$data = DB::table('tvip_cost_order')->where(['node_id'=>$node_id,'status'=>1])->orderBy('id','desc')->get();

//		dd($data);
        //如果是post请求
        if($request->isMethod('post') && $data->isEmpty()) {
            exit('暂无数据');
        }

		//解析支付详情
		foreach($data as $key => $value) {
			$data[$key]->pay_detail = json_decode($value->pay_detail, true);
		}

		//展示模板
		return view('admin.ucenter.ucenter_vip_cost',['data'=>$data,'nodename'=>$nodename]);
	}

	/**
	 * 用户购买的代购套餐
	 */
	public function ucenter_pur_cost(Request $request) {
		//获取请求参数
		$nodename = $request->input('nodename');
		$node_id  = $request->input('id');

		//查询用户代购套餐
		$where['node_id']    = $node_id;
		$where['order_type'] = 2;
		$data     = DB::table('tbuy_order')->where($where)->orderBy('order_id','desc')->get();

		//如果是post请求
		if($request->isMethod('post') && $data->isEmpty()) {
			exit('暂无数据');
		}

		//展示模板
		return view('admin.ucenter.ucenter_pur_cost',['data'=>$data,'nodename'=>$nodename]);
	}

	/**
	 * 用户购买的直销套餐
	 **/
	public function ucenter_direct_cost(Request $request) {
		//获取用户的ID和用户名
		$node_id = $request->input()['id'];
		$nodename = $request->input()['nodename'];
		//查询用户信息
		$data = DB::table('tvip_direct_order')
				->select('tvip_direct_order.*','tvip_direct.name')
				->leftJoin('tvip_direct', 'tvip_direct_order.direct_id', '=', 'tvip_direct.id')
				->where(['node_id'=>$node_id])
				->orderBy('tvip_direct_order.id','desc')
				->get();

		//解析支付详情
		foreach($data as $key => $value) {
			$data[$key]->pay_detail = json_decode($value->pay_detail, true);
		}

		//展示模板
		return view('admin.ucenter.ucenter_direct_cost',['data'=>$data,'nodename'=>$nodename]);
	}

	/**
	 * 用户线上订单
	 **/
	public function ucenter_online_order(Request $request) {
		//查询用户线上订单信息
		$nodename = $request->input('nodename');
		$node_id = $request->input('id');
		$data = DB::table('tbuy_order')->where(['node_id'=>$node_id])->orderBy('order_id','desc')->get();

        //如果是post请求
        if($request->isMethod('post') && $data->isEmpty()) {
            exit('暂无数据');
        }

		//解析支付详情（支付组合）
		foreach($data as $key => $value) {
			$data[$key]->pay_type_group = json_decode($value->pay_type_group, true);
		}
		//展示模板
		return view('admin.ucenter.ucenter_online_order',['data'=>$data,'nodename'=>$nodename]);
	}

	/**
	 * 用户详情
	 **/
	public function ucenter_details(Request $request) {
		//查询用户信息
		$nodeid = $request->input()['id'];
		$user_info = DB::table('tnet_reginfo')->where(['nodeid'=>$nodeid])->first();

		//查询推荐人信息
		if($user_info->introducer) {
			$parent_info = DB::table('tnet_reginfo')->select('nodename')->where(['nodeid'=>$user_info->introducer])->first();
			//保存推荐人信息
			$user_info->parent_name = $parent_info->nodename;
		}

		//查询用户对应的身份证信息
		$document_info = DB::table('tnet_user_documents')->where(['node_id'=>$user_info->nodeid])->first();
		if($document_info) {
			$identity_info = DB::table('tnet_identity')->where(['id'=>$document_info->documents_id])->first();
		}

		//查询用户对应的银行卡信息
		$bank_info = DB::table('tnet_bank_account')->where(['node_id'=>$user_info->nodeid])->get();

		//查询用户对应的钱包信息
//		$purse_info = DB::table('tblc_user_purse')->where(['ownerid'=>$user_info->nodeid])->get();

		//保存用户的身份证信息，银行卡信息，钱包信息到用户集合中（user_info）
		/*******************身份证信息*********************/
		if($document_info) {
			$user_info->identity_id 	= $identity_info->id;
			$user_info->identity_name 	= $identity_info->user_name;
			$user_info->identity_no 	= $identity_info->identity_no;
			$user_info->birthday 		= $identity_info->birthday;
			$user_info->sex 			= $identity_info->sex;
			$user_info->nation 			= $identity_info->nation;
			$user_info->begin_time 		= $identity_info->begin_time;
			$user_info->end_time 		= $identity_info->end_time;
			$user_info->issuing 		= $identity_info->issuing;
			$user_info->identity_status = $identity_info->status;
			$user_info->address  	  	= $identity_info->address;
			$user_info->head_photo    	= $identity_info->head_photo;
			$user_info->front_photo   	= $identity_info->front_photo;
			$user_info->back_photo 	  	= $identity_info->back_photo;
			$user_info->identity_time 	= $identity_info->create_time;
		}else {
			$user_info->identity_id 	= 0;
		}

		/*******************银行卡信息*********************/
		$user_info->bank_info = $bank_info;

		/******************是否购买区待********************/
		$project_data = Db::table('tvip_project_order')
						->where('status',1)
						->where('node_id',$user_info->nodeid)
						->first();
		$user_info->is_project = $project_data ? 1 : 0;

		/*****************是否手机区待*********************/
		$phone_agent_data = Db::table('tvm_agent_order')
							->where('status',1)
							->where('node_id',$user_info->nodeid)
							->first();
		$user_info->is_phone_agent = $phone_agent_data ? 1 : 0;
		
		/*******************钱包信息*********************/
        //获取用户钱包ID号
//        $node_id = $user_info->nodeid;
//        #走接口获取数据流
//        $data['_cmd']='usercenter_wallet';
//        $data['ticket']=$this->get_ticket($node_id);
//        #获取任务明细
//        $res = $this->api_post($data);
//        $user_info->purse_info = $res['data'];
//        dd($user_info);
		//展示模板
		return view('admin.ucenter.ucenter_details',['user_info'=>$user_info]);
	}

	/**
	 +----------------------------------------------------------
	 * 手动报单相关
	 +----------------------------------------------------------
	 */
	/**
	 * 手动报单
	 **/
	public function team_recharge(Request $request) {
		if($request->isMethod('post')){
			$data = $post = $request->all();
			$data['_cmd'] = 'admin_team_recharge';
			$data['ticket'] = '';
			//提交数据给接口
			$result = $this->api_post($data);
			if($result['status'] == '1') {
				//记录文件日志
				record_action(AdminAction::getNextSeq(),'Ucenter','team_recharge','手动报单',json_encode($post));
			}
			return response()->json($result);
		}
		return view('admin.ucenter.team_recharge' , []);
	}

	/**
	 * 查找出用户的推荐人信息
	 */
	public function get_user_introducer(Request $request){
		$nodecode = $request->input('nodecode');

		$ucenterModel = new Ucenter();
		$node = $ucenterModel->get_user_by_nodecode($nodecode);
		if(!$node){
			return response()->json([]);
		}
		$node->vipLevel = $ucenterModel->vip_level($node->nodeid);

		$introducer = $ucenterModel->get_user_info_by_id($node->introducer);
		$introducer->vipLevel = $ucenterModel->vip_level($introducer->nodeid);

		$introducer2 = $ucenterModel->get_user_info_by_id($introducer->introducer);
		$introducer2->vipLevel = $ucenterModel->vip_level($introducer2->nodeid);

		$data = [
			'node' => $node,
			'intro' => $introducer,
			'intro2' => $introducer2,
		];

		return response()->json($data);
	}

	/**
	 * 查看手动报单列表
	 */
	public function team_recharge_list(Request $request){
		// $adminActionModel = new AdminAction();
		$condition['action'] = 'team_recharge';
		$action_list = $data = DB::table('admin_action')->where($condition)->orderBy('action_id','desc')->paginate(3);
		//展示模板
        return view('admin.ucenter.action_list',['action_list'=>$action_list]);
	}

	/**
	 * 查看手动报单详情
	 */
	public function team_recharge_detail(Request $request){
		//查询管理员行为日志信息（ID号）
		$data = DB::table('admin_action')->where('action_id',$request->input('id'))->first();
		//解析请求参数信息
		$data->request = json_decode($data->request_info,true);
		//暂时不用_token字段
		unset($data->request['_token']);
		//展示模板
		return view('admin.ucenter.action_detail',compact('data'));
	}

	/**
	 * 用户钱包余额
	 **/
	public function ucenter_purse(Request $request) {
        //获取用户钱包ID号
        $node_id = $request->input('id');

        #走接口获取数据流
        $data['_cmd']='usercenter_wallet';
        $data['ticket']=$this->get_ticket($node_id);
//        dd($data);
        #获取任务明细
        $res = $this->api_post($data);
//        dd($res,$data);
        return view('admin.ucenter.ucenter_purse',['data'=>$res['data'],'node_id'=>$node_id]);
	}

	/**
	 * 用户流水信息
	 **/
	public function user_transfer(Request $request) {
	    //获取接口需要的参数信息
        $node_id        = $request->input('node_id');
        $data['_cmd']   = 'usercenter_bill';
        $data['ticket'] = $this->get_ticket($node_id);
        $data['type']   = $request->input('type');
        $into           = $request->input('into');

        //转账类型
        if($into == 1) { //转出
            $data['into'] = 1;
        }else if($into == 2) { //转入
            $data['into'] = 2;
        }else { //全部
            $data['into'] = 0;
        }
        $data['pagesize'] = 100;
        $data['page'] = $request->input('page') ? $request->input('page') : 1;
        // dd($data);

        $res = $this->api_post($data);

        return view('admin.ucenter.user_transfer',[
            'data'    => $res['data'],
            'into'    => $data['into'],
            'node_id' => $node_id,
            'type'    => $data['type']
        ]);
    }

    public function ajax_user_transfer(Request $request) {
        //获取接口需要的参数信息
        $node_id = $request->input('node_id');
        $data['_cmd'] = 'usercenter_bill';
        $data['ticket']=$this->get_ticket($node_id);
        $data['type'] = $request->input('type');
        $into = $request->input('into');
        $data['page'] = $request->input('page');
        if($into == 1) {
            $data['into'] = 1;
        }else if($into == 2) {
            $data['into'] = 2;
        }else {
            $data['into'] = 0;
        }
        $data['pagesize'] = $request->input('pagesize');

        $res = $this->api_post($data);
        $arr = array();
        foreach($res['data'] as $key => $value) {
            foreach($value['children'] as $val) {
                $arr[] = $val;
            }
        }
        echo json_encode($arr);
        exit;
    }

    /**
     * 注册用户
     */
    public function user_register(Request $request) {
        //如果是post请求，则提交给接口
        if($request->isMethod('post')) {
            //准备接口需要的参数
            $data['introducer'] = $request->input('introducer');
            $data['mobile_no'] = $request->input('mobile_no');
            $data['_cmd'] = 'admin_register';
            $data['ticket']='';
            //提交数据给接口
            // dd($data);
            $result = $this->api_post($data);
            if($result['info'] == '注册成功') {
            	record_action(AdminAction::getNextSeq(),'Ucenter','user_register','注册用户',json_encode($_POST));
            }
            // var_dump($result);
            exit(json_encode($result,true));
        }else {
            return view('admin.ucenter.user_register');
        }
    }

    /**
     * 修改用户成为VIP
     */
    public function modify_user_to_vip(Request $request) {
        //如果是POST请求
        if($request->isMethod('post')) {
            //获取提交的数据
            $data['mobile_no'] = $request->input('mobile_no');
            $data['_cmd'] = 'admin_set_vip';
            $data['ticket'] = '';
            //提交数据给接口
            $result = $this->api_post($data);
         	if($result['info'] == '操作成功') {
         		record_action(AdminAction::getNextSeq(),'Ucenter','modify_user_to_vip','修改用户成为VIP',json_encode($_POST));
         	}
            exit(json_encode($result,true));
        }else {
            return view('admin.ucenter.modify_user_to_vip');
        }
    }

    /**
     * 返还储值积分
     */
    public function recharge_integral(Request $request) {
        //如果是POST请求方式
        if($request->isMethod('post')) {
            //准备接口需要的数据
            $data['mobile_no'] = $request->input('mobile_no');
            $data['amount'] = $request->input('amount');
            $data['_cmd'] = 'admin_virtual_cost_buy';
            $data['ticket'] = '';
            //提交数据给接口
            $result = $this->api_post($data);
            if($result['info'] == '操作成功') {
                //记录文件日志
                record_action(AdminAction::getNextSeq(),'Ucenter','recharge_integral','返还储值积分',json_encode($_POST));
                // $node_id = $_SESSION['admin_uid'];
                // $result = DB::table('tnet_reginfo')->where(['nodeid'=>$node_id])->first();
                // filedebug('管理员ID号'.$node_id.'管理员'.$result->nodename.
                //           '充值用户手机号'.$data['mobile_no'].'充值金额'.$data['amount'],
                //           './log/Ucenter/recharge_integral.php');
            }
            exit(json_encode($result,true));
        }
        return view('admin.ucenter.recharge_integral');
    }

    /**
     * 获取ticket
     */
    public function post_get_ticket(Request $request) {
        $node_id = $request->input('node_id');
        $sessionInfo=DB::table('tsso_session')
            ->where('node_id','=',$node_id)
            ->select('ticket')
            ->orderBy('sid','desc')
            ->first();
        if(!$sessionInfo) {
            return '';
        }
        return $sessionInfo->ticket;
    }
}